﻿using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using MoBaoPay.Model;
using Newtonsoft.Json;

namespace MoBaoPay
{
    public static class HttpClientExtensions
    {
        /// <summary>
        /// 发起摩宝http请求
        /// </summary>
        /// <typeparam name="T">返回数据对象</typeparam>
        /// <param name="client">http对象</param>
        /// <param name="request">请求实体</param>
        /// <returns></returns>
        public static async Task<MoBaoResponse<T>> PostAsync<T>(this HttpClient client, IMoBaoRequest request) where T : class
        {
            var url = request.GetRequestUrl();

            var boundary = DateTime.Now.Ticks.ToString("X");
            using var reqContent = new MultipartFormDataContent(boundary);
            foreach (var item in request.GetRequestContent())
            {
                reqContent.Add(new StringContent(item.Value ?? string.Empty, Encoding.UTF8, "text/plain"), $"\"{item.Key}\"");
            }
            using var resp = await client.PostAsync(url, reqContent);
            var response = await resp.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<MoBaoResponse<T>>(response);
        }
    }
}